<?php

class ReaderController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'ajaxOnly + addMoney',
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','addMoney'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','addMoney'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Reader;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Reader']))
		{
			$model->attributes=$_POST['Reader'];
			if($model->save())
			{
				//先记录操作
				$this->LogRecord($model->readerID, Logs::READER_CREATE, '');
				
				$this->redirect(array('view','id'=>$model->readerID));
			}
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Reader']))
		{
			$model->attributes=$_POST['Reader'];
			if($model->save())
			{
				//先记录操作
				$this->LogRecord($model->readerID, Logs::READER_UPDATE, '');
				
				$this->redirect(array('view','id'=>$model->readerID));
			}
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$model1 = $this->loadModel($id);
			
// 			->delete();
			//记录被删除的读者信息简要
			$descript = '读者编号：' . $model1->readerID . '；读者姓名：' . $model1->name .'；联系电话：'. $model1->phoneNum . '；证件：' . $model1->IDType . $model1->IDNum ;
			if($model1->delete())
				$this->LogRecord($model1->readerID, Logs::READER_DEL, $descript);
			
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Reader');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Reader('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Reader']))
			$model->attributes=$_GET['Reader'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Reader::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='reader-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	/**
	 * 记录对读者信息的新建、更新、删除操作和事件。
	 * @param 整数 $id 是读者的ID
	 * @param 字符串 $action 是对读者的操作类型表述
	 * @param 字符串 $descipt 是对操作的补充描述
	 */
	protected function LogRecord($id,$action,$descipt){
		$rec = new Logs();
		$rec->bookID = $id;
		$rec->name = Yii::app()->user->name;
		$rec->operate = $action;
		$rec->date = date("Y-m-d H:i:s");
		$rec->descript = $descipt;
		$rec->optTable = Logs::OPT_TAB_READER;
	
		$rec->save();
	
	}
	
	/**
	 * 仅接受AJAX调用。为用户进行充值操作。
	 * @param int $id 读者编号。
	 * @param float $money 货币数。
	 */
	public  function actionAddMoney($id,$money){
		$model= new Reader();
		if($model->findByPk($id)){
			$model->balance = $money;
			if($model->save())
			{//做下操作记录
				LogRecord($id,Reader::ADD_MONEY,'');
				return;
			}
		}
		
		throw new CHttpException(500,'未知错误！请联系管理员！');
	} 
}
